<template>
    <el-card>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            status-icon>

            <el-row :gutter="20">
                <el-col :md="9" :sm="14" :xs="24">
                    <el-form-item label="标题" prop="title">
                        <el-input size="large" v-model="ruleForm.title" />
                    </el-form-item>
                </el-col>
                <el-col :sm="14" :md="8" :xs="20">
                    <el-form-item label="类别" prop="categoryId">
                        <el-select-v2 :props="props" v-model="value" :options="options" placeholder="Please select"
                            size="large" />
                    </el-form-item>
                </el-col>
                <el-col :sm="8" :md="6" :xs="4">
                    <el-button @click="handleConfirm" size="large" type="primary">
                        {{ useArticleStore().title }}
                    </el-button>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :md="14" :xs="24">
                    <el-form-item label="摘要" prop="summary">
                        <el-input :autosize="{ minRows: 4, maxRows: 6 }" v-model="ruleForm.summary" type="textarea" />
                    </el-form-item>
                </el-col>
                <el-col :md="10" :xs="24">
                    <el-form-item label="状态" prop="status">
                        <el-radio-group size="large" v-model="ruleForm.status">
                            <el-radio :value="0" size="large" border>发布</el-radio>
                            <el-radio :value="1" size="large" border>草稿</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="图片">
                <el-upload ref="uploadRef" v-model:file-list="fileList" list-type="picture-card" :auto-upload="false">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <MdEditor :disabled-menus="[]" @onUploadImg="handleUploadImage" v-model="ruleForm.content">
                </MdEditor>
            </el-form-item>

        </el-form>
    </el-card>
</template>


<script setup>
import { reactive, ref, computed } from 'vue';
import { MdEditor } from 'md-editor-v3';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useArticleStore } from '@/store/article/index.js'
import { UploadImgAPI, categoriesAPI, addArticleAPI, updateArticleAPI } from '@/api'
import 'md-editor-v3/lib/style.css';

const $router = useRouter()

const originalroleData = () => ({
    id: '',
    content: '',
    thumbnail: '',
    status: 0,
    summary: '',
    title: '',
    categoryId: ''
})

const uploadRef = ref()
const fileList = ref([])
let ruleForm = reactive(originalroleData())

const rules = reactive({
    title: [
        { required: true, message: 'Please input ', trigger: 'blur' },
    ],
})

const handleUploadImage = async (files, callback) => {
    const res = await Promise.all(
        files.map((file) => {
            return new Promise((rev, rej) => {
                const form = new FormData();
                form.append('file', file);

                UploadImgAPI(form)
                    .then((res) => rev(res))
                    .catch((error) => rej(error));
            });
        })
    );

    callback(res.map((item) => item));
}

const options = ref([])
const value = ref('')
const props = ref({
    label: "name",
    value: "id",
});
const getCategories = async () => {
    const res = await categoriesAPI()
    options.value = res
}

const initValue = () => {
    ruleForm = useArticleStore().articleValue
    if (useArticleStore().id != -1) {
        let img = []
        let obj = {}
        obj.url = ruleForm.thumbnail
        img.push(obj)
        fileList.value = img
        value.value = ruleForm.categoryId
    }
}

initValue()

getCategories()

const handleConfirm = async () => {
    const formData = new FormData()
    if (fileList.value[0].raw) {
        formData.append("file", fileList.value[0].raw)
        const res = await UploadImgAPI(formData)
        ruleForm.thumbnail = res
    }
    ruleForm.categoryId = value.value
    let rus = ref()
    let ras = ref()
    if (useArticleStore().id == -1) {
        ras.value = await addArticleAPI(ruleForm)
        rus.value = "添加成功"
    }
    else {
        ras.value = await updateArticleAPI(ruleForm)
        rus.value = "更新成功"
    }
    if (ras.value != false) {
        ElMessage.success(rus.value)
        Object.assign(ruleForm, originalroleData())
        uploadRef.value.clearFiles()
        useArticleStore().reset()
        $router.push({
            path: "/content/articleList"
        })
    }
}


</script>


<style lang="scss" scoped></style>